package com.zhouyu.mybatis.spring;

import com.zhouyu.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 周瑜
 */

public class ZhouyuFactoryBean implements FactoryBean { // zhouyuFactoryBean--->UserMapper代理对象

	private Class mapperInterface;

	private SqlSession sqlSession;

	public ZhouyuFactoryBean(Class mapperInterface) {
		this.mapperInterface = mapperInterface;
	}

	@Autowired
	public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
		//这里就要注入配置类中的@Bean定义的SqlSessionFacory
		//然后每个mapperBean单例都会对应到一个sqlSession会话
		//Mybatis中，设置的是sqlSessionTemplate 这个是一个封装了sqlSqlSession动态代理的类，动态代理内部
		//InvocationHandler在执行每个方法时，通过Spring的TransactionSynchronizationManager.getResource(sessionFactory)
		//从当前事务中获取sqlSession ，否则就通过sqlSessionFactory开启新的sqlSession
		sqlSessionFactory.getConfiguration().addMapper(mapperInterface);
		this.sqlSession = sqlSessionFactory.openSession();
	}

	@Override

	public Object getObject() throws Exception {
		//这里与mybatis不同，mybatis是调用getSqlSession来获取的
		return sqlSession.getMapper(mapperInterface);
	}

	@Override
	public Class<?> getObjectType() {
		return mapperInterface;
	}
}
